using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace Lib
{
    public class RegexDataProcessor : IDataProcessor 
    {
        private bool _invokeAsync;
        private readonly Dictionary<Regex, Action<GroupCollection>> _triggers;

        public RegexDataProcessor() : this(false) {}

        public RegexDataProcessor(bool invokeAsynchronously)
        {
            _invokeAsync = invokeAsynchronously;
            _triggers = new Dictionary<Regex, Action<GroupCollection>>();
        }

        public void Register(string regexPattern, Action<GroupCollection> function)
        {
            var expression = new Regex(regexPattern);
            _triggers.Add(expression, function);
        }

        void IDataProcessor.Process(string data)
        {
            foreach(var pair in _triggers)
            {
                Match m = pair.Key.Match(data);
                if(!m.Success)
                    continue;

                try
                {
                    if (_invokeAsync)
                        pair.Value.BeginInvoke(m.Groups, ProcessCallback, pair.Value);
                    else
                        pair.Value.Invoke(m.Groups);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
        }

        private static void ProcessCallback(IAsyncResult result)
        {
            ((Action<GroupCollection>)result.AsyncState).EndInvoke(result);
        }
    }
}